package com.xiaoye.qbdatahandle.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
@Service
public class FileDownloadService {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 流式下载大文件并保存到本地
     *
     * @param fileUrl  文件 URL
     * @param savePath 保存路径（包括文件名）
     * @throws IOException 如果文件操作失败
     */
    public void downloadLargeFile(String fileUrl, String savePath) throws IOException {
        if (fileUrl == null || savePath == null) {
            return;
        }
        // 创建保存目录（如果不存在）
        Files.createDirectories(Paths.get(savePath).getParent());
        log.debug("开始下载文件：{}", fileUrl);
        // 下载文件
        ResponseEntity<Resource> response = restTemplate.getForEntity(fileUrl, Resource.class);
        try (InputStream inputStream = response.getBody().getInputStream();
             FileOutputStream fos = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
        log.debug("文件下载完成:{}",savePath);
    }
}